package com.cql.framework.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.cql.common.constant.HttpStatus;
import com.cql.common.core.base.AjaxResult;
import com.cql.common.core.security.LoginUser;
import com.cql.common.utils.ServletUtils;
import com.cql.common.utils.StringUtils;
import com.cql.framework.config.security.service.TokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 退出登录
 *
 * @author cql
 */
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private TokenService tokenService;

    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        /**
         * 退出登录：
         * 1.删除redis中信息，
         * 2.记录日志
         */
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            logger.info("{} 退出登录", loginUser.getUserDO().getAccount());
        }
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(HttpStatus.OK.getCode(), "退出成功")));
    }
}

